<!--
 * @Description: 支持配置式的 饿了么table组件， 二次开发
 * @Author bianpengfei
 * @create 2021/4/26 23:05
 -->
<template>
  <g-spin :loading="loading" v-bind="loadingAttrs">
    <el-table v-bind="$attrs" v-on="$listeners">
      <template slot="empty">
        <g-empty style="height: 120px"></g-empty>
      </template>

      <!--一层-->
      <template v-for="_1 in _columns">
        <el-table-column :key="_1.key" v-bind="_1">
          <template v-if="_1.slotName" v-slot="scope">
            <slot :name="_1.slotName" v-bind="scope"></slot>
          </template>
        </el-table-column>
        <!--二层-->
        <template v-if="Array.isArray(_1.children) && _1.children.length">
          <template v-for="_2 in _1.children">
            <el-table-column :key="_2.key" v-bind="_2">
              <template v-if="_2.slotName" v-slot="scope">
                <slot :name="_2.slotName" v-bind="scope"></slot>
              </template>
            </el-table-column>

            <!--三层-->
            <template v-if="Array.isArray(_2.children) && _2.children.length">
              <template v-for="_3 in _2.children">
                <el-table-column :key="_3.key" v-bind="_3">
                  <template v-if="_3.slotName" v-slot="scope">
                    <slot :name="_3.slotName" v-bind="scope"></slot>
                  </template>
                </el-table-column>

                <!--四层-->
                <template v-if="Array.isArray(_3.children) && _3.children.length">
                  <template v-for="_4 in _3.children">
                    <el-table-column :key="_4.key" v-bind="_4">
                      <template v-if="_4.slotName" v-slot="scope">
                        <slot :name="_4.slotName" v-bind="scope"></slot>
                      </template>
                    </el-table-column>
                  </template>
                </template>
              </template>
            </template>
          </template>
        </template>
      </template>

      <!-- 默认插槽   -->
      <slot></slot>
    </el-table>
  </g-spin>
</template>

<script>
export default {
  name: 'GTable',

  inheritAttrs: false,
  props: {
    columns: {
      // 字段
      type: Array,
      default: () => []
    },
    loading: {
      type: Boolean,
      default: false
    },
    loadingAttrs: {
      // spin配置信息，详情传参见 spin
      type: Object,
      default: () => ({})
    }
  },

  computed: {
    _columns() {
      return this.changeSlotName(this.columns) || []
    }
  },

  methods: {
    changeSlotName(data) {
      data.forEach((v, vi) => {
        if (v.slot) {
          v.slotName = v.slot
          delete v.slot
        }
        v.key = `${vi}${Math.random().toString(32).substring(2)}${Math.random().toString(32).substring(2)}`
        if (Array.isArray(v.children)) {
          this.changeSlotName(v.children)
        }
      })
      return data
    }
  }
}
</script>
